<template>
<div class="relative p-6 space-y-6">
  <!-- 搜索区域 -->
  <div class="glass-card p-6">
    <div class="space-y-6">
      <!-- 主搜索框 -->
      <div class="relative">
        <Search class="absolute left-4 top-1/2 transform -translate-y-1/2 text-accent w-6 h-6" />
        <input v-model="searchQuery" type="text" placeholder="      输入政策名称、关键词或部门名称进行搜索..."
          class="w-full pl-12 pr-20 py-4 cyber-input text-lg" @keypress="handleKeyPress" />
        <button @click="performSearch"
          class="absolute right-2 top-1/2 transform -translate-y-1/2 cyber-button px-6 py-2">
          搜索
        </button>
      </div>

        <!-- 行业标签筛选 -->
        <div class="grid grid-cols-1 lg:grid-cols-4 gap-8">
          <div class="lg:col-span-3">
            <label class="block text-primary text-lg font-medium mb-4">
              🏷️ 行业标签筛选
              <span class="text-primary/60 text-sm ml-3">
                (选择相关行业标签，精准匹配政策)
              </span>
            </label>
            <div class="glass-card p-8 min-h-[500px]">
              <TagSelector
                v-model="selectedTags"
                :max-selection="10"
                :all-tags="groupedAllTags"
                :all-popular-tags="popularTags"
                @change="handleTagsChange"
                @max-selection-reached="handleMaxSelectionReached"
              />
            </div>
          </div>

          <div>
            <label class="block text-primary text-lg font-medium mb-4">
              📊 筛选统计
            </label>
            <div class="space-y-4 sticky top-6">
              <div class="glass-card p-6 text-center">
                <div class="text-3xl font-bold text-accent mb-2">{{ selectedTags.length }}</div>
                <div class="text-primary/70 text-base">已选标签</div>
              </div>
                <div class="glass-card p-6 text-center">
                <div class="text-3xl font-bold text-yellow-400 mb-2">{{ totalPolicyCount }}</div>
                <div class="text-primary/70 text-base">匹配政策</div>
                </div>
              <div v-if="selectedTags.length > 0" class="glass-card p-4">
                <div class="text-primary/70 text-sm mb-3 font-medium">当前筛选标签:</div>
                <div class="flex flex-wrap gap-2">
                  <span v-for="tag in selectedTags.slice(0, 4)" :key="tag"
                    class="px-3 py-2 bg-electric-500/20 text-electric-300 rounded-full text-sm font-medium tag-chip">
                    {{ tag }}
                  </span>
                  <span v-if="selectedTags.length > 4" class="text-primary/60 text-sm py-2">
                    +{{ selectedTags.length - 4 }}个...
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索结果统计 -->
    <div class="flex items-center justify-between">
      <div class="text-primary/70">
        找到 <span class="text-accent font-semibold">{{ totalPolicyCount }}</span> 条相关政策
      </div>
      
    </div>

   <!-- 政策列表 -->
<div v-if="isLoading" class="text-center py-12">
  <div class="text-electric-400 text-lg">加载中...</div>
</div>
<div v-else class="space-y-4">
  <div v-for="policy in paginatedPolicies" :key="policy.id"
    :class="[
      'glass-card p-6 hover:cyber-glow transition-all duration-300 cursor-pointer relative',
      isSelected(policy) ? 'ring-2 ring-electric-500 bg-electric-500/10' : ''
    ]"
    @click="togglePolicySelection(policy)">
    <div class="flex flex-col lg:flex-row lg:items-start lg:justify-between gap-4">
      <!-- 选中状态指示器 -->
      <div class="absolute top-6 left-3 flex items-center z-10">
        <div v-if="isSelected(policy)" 
             class="relative w-4 h-4 bg-gradient-to-br from-electric-400 to-cyan-500 flex items-center justify-center shadow-sm">
          <svg class="w-3 h-3 text-white relative z-10" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7"></path>
          </svg>
        </div>
        <div v-else class="w-4 h-4 border border-electric-500/40 bg-transparent hover:border-electric-500/70 transition-all duration-300"></div>
      </div>
      <div class="flex-1 ml-8">
        <div class="flex items-start justify-between mb-3">
          <h3 class="text-xl font-semibold text-primary mb-2 flex-1"
              @mouseenter="onPolicyTitleEnter(policy, $event)"
              @mouseleave="onPolicyTitleLeave">
            {{ policy.title }}
          </h3>
          <div class="flex flex-col items-end space-y-2">
            <span :class="getStatusClass(inferPolicyStatus(policy))">
              {{ inferPolicyStatus(policy) }}
            </span>
            <div class="text-right text-xs text-primary/70">
              <!-- 修改生效日期字段 -->
              <div>{{ formatDate(policy.start_time) }}</div>
              <!-- 修改失效日期字段 -->
              <div v-if="policy.end_time">至 {{ formatDate(policy.end_time) }}</div>
            </div>
          </div>
        </div>
        <div class="flex items-center space-x-6 text-sm text-primary/70 mb-3">
          <div class="flex items-center space-x-1">
            <Building class="w-4 h-4" />
            <span>{{ policy.department }}</span>
          </div>
          <div class="flex items-center space-x-1">
            <Calendar class="w-4 h-4" />
            <!-- 修改发布日期字段 -->
            <span>{{ formatDate(policy.publish_time) }}</span>
          </div>
          <div class="flex items-center space-x-1">
            <MapPin class="w-4 h-4" />
            <!-- 修改地区字段 -->
            <span>{{ policy.address_1 }}</span>
          </div>
          <div class="flex items-center space-x-1">
            <Tag class="w-4 h-4" />
            <!-- 修改类别字段 -->
            <span>{{ policy.type }}</span>
          </div>
        </div>
        <!--<p class="text-primary/80 text-sm mb-4 line-clamp-3">{{ policy.summary }}</p>-->
        <!-- 标签区域 -->
        <div class="flex flex-wrap gap-2">
          <!-- 处理标签字段，优先显示已转换的中文标签 -->
          <span v-for="tag in getDisplayTags(policy)" 
                :key="tag"
                :class="['px-2 py-1 rounded text-xs cursor-pointer transition-colors',
                         selectedTags.includes(tag) 
                           ? 'bg-electric-500/30 text-electric-300 ring-1 ring-electric-500/50' 
                           : 'bg-tech-blue-500/20 text-tech-blue-300 hover:bg-tech-blue-500/30']"
                @click.stop="quickFilterByTag(tag)">
            {{ tag }}
          </span>
          <!-- 如果没有标签，显示政策类型 -->
          <span v-if="getDisplayTags(policy).length === 0 && policy.type"
                class="px-2 py-1 bg-gray-500/20 text-gray-400 rounded text-xs">
            {{ policy.type }}
          </span>
        </div>
      </div>
      <div class="flex lg:flex-col space-x-2 lg:space-x-0 lg:space-y-2">
        <button @click.stop="viewPolicy(policy)" class="cyber-button flex items-center space-x-2 whitespace-nowrap">
          <Eye class="w-4 h-4" />
          <span>查看详情</span>
        </button>
        <button @click.stop="downloadPolicy(policy)"
          class="bg-electric-500 hover:bg-electric-600 text-cyber-50 px-4 py-2 rounded-lg transition-colors flex items-center space-x-2 whitespace-nowrap">
          <Download class="w-4 h-4" />
          <span>下载</span>
        </button>
        <button @click.stop="collectPolicy(policy)"
          class="bg-yellow-500 hover:bg-yellow-600 text-cyber-50 px-4 py-2 rounded-lg transition-colors flex items-center space-x-2 whitespace-nowrap">
          <Bookmark class="w-4 h-4" />
          <span>收藏</span>
        </button>
      </div>
    </div>
  </div>
  <!-- 政策之窗弹窗 -->
  <PolicyWindow v-if="showPolicyWindow && policyWindowData"
    :policy="policyWindowData"
    :style="{ position: 'absolute', left: policyWindowPosition.x + 'px', top: policyWindowPosition.y + 'px', zIndex: 9999 }"
    @mouseenter="onPolicyWindowEnter"
    @mouseleave="onPolicyWindowLeave"
    @go-detail="handleGoDetail"
  />
</div>

    <!-- 分页 -->
    <div class="flex items-center justify-center space-x-4">
      <button @click="previousPage" :disabled="currentPage === 1" class="cyber-button px-4 py-2 disabled:opacity-50">
        上一页
      </button>

      <div class="flex items-center space-x-2">
        <button v-for="page in visiblePages" :key="page" @click="goToPage(page)" :class="[
          'px-3 py-2 rounded-lg transition-colors',
          page === currentPage
            ? 'bg-electric-500 text-cyber-50'
            : 'text-primary/70 hover:text-primary hover:bg-white/10'
        ]">
          {{ page }}
        </button>
      </div>

      <button @click="nextPage" :disabled="currentPage === totalPages"
        class="cyber-button px-4 py-2 disabled:opacity-50">
        下一页
      </button>
    </div>

    <!-- 空状态 -->
    <div v-if="policies.length === 0 && !isLoading" class="text-center py-12">
      <Search class="w-16 h-16 text-accent mx-auto mb-4" />
      <p class="text-primary/70 mb-2">未找到匹配的政策</p>
      <p class="text-primary/50 text-sm">请尝试调整搜索条件或筛选选项</p>
    </div>

    <!-- 批量操作 -->
    <!-- 批量操作按钮组 -->
  </div>

  <!-- 浮动对比按钮 - 使用 Teleport 确保在最顶层 -->
  <Teleport to="body">
    <div v-if="selectedPolicies.length > 0" 
         class="fixed bottom-6 right-6 glass-card p-4 rounded-xl shadow-2xl"
         style="z-index: 9999; pointer-events: auto;">
      <div class="flex items-center space-x-4">
        <span class="text-primary">{{ t('selectedPolicies', { count: selectedPolicies.length }) }}</span>
        <button 
          @click="navigateToCompareCenter" 
          class="cyber-button flex items-center space-x-2"
          :disabled="selectedPolicies.length < 2"
        >
          <GitCompare class="w-4 h-4" />
          <span>{{ t('gotoCompareCenter') }}</span>
        </button>
        <button @click="clearSelection" class="text-primary/70 hover:text-primary transition-colors">
          <X class="w-4 h-4" />
          <span>{{ t('compareCancel') }}</span>
        </button>
      </div>
    </div>
  </Teleport>

  <!-- 对比分析弹窗 - 使用 Teleport 确保在最顶层显示 -->
  <!-- 移除原有的对比弹窗，改为跳转到政策中心 --> 


  <!-- 政策之窗弹窗 - 使用 Teleport 确保在最顶层显示 -->
  <Teleport to="body">
    <PolicyWindow v-if="showPolicyWindow && policyWindowData"
      :policy="policyWindowData"
      :style="{ position: 'fixed', left: policyWindowPosition.x + 'px', top: policyWindowPosition.y + 'px', zIndex: 99998 }"
      @mouseenter="onPolicyWindowEnter"
      @mouseleave="onPolicyWindowLeave"
      @go-detail="handleGoDetail"
    />
  </Teleport>
</template>

<script>
import PolicyWindow from '../components/PolicyWindow.vue'
import themeService, { themeState } from '../services/themeService.js'
import {
  Search,
  Filter,
  Eye,
  Download,
  Bookmark,
  Calendar,
  Tag,
  Building,
  MapPin,
  Star,
  GitCompare,
  X,
  BarChart3
} from 'lucide-vue-next'
import TagSelector from '../components/TagSelector.vue'
import tagService from '../services/tagService.js'
import VChart from 'vue-echarts'
import * as echarts from 'echarts'
import 'echarts-wordcloud'
import {translatePageContent, setCurrentLanguage } from '../directives/translate.js'
import axios from 'axios'
import RegionCascader from '../components/RegionCascader.vue'
import CategorySelector from '../components/CategorySelector.vue'
import DepartmentSelector from '../components/DepartmentSelector.vue'
import StatusSelector from '../components/StatusSelector.vue'

export default {
  name: 'PolicyQuery',
  components: {
    GitCompare,
    X,
    BarChart3,
    PolicyWindow,
    VChart,
    Search,
    Filter,
    Eye,
    Download,
    Bookmark,
    Calendar,
    Tag,
    Building,
    MapPin,
    Star,
    TagSelector,
    RegionCascader
  },
  inject: ['globalState'],
  computed: {
    currentLanguage() {
      return this.globalState.currentLanguage
    },
    translations() {
      return {
        zh: {
          policyQuery: '政策查询',
          intelligentPolicySearchSystem: '智能政策搜索与查询系统',
          policyAnalysis: '政策分析',
          policyAnalysisSystem: '政策文件智能分析与对比系统',
          policyList: '政策列表',
          policyComparison: '政策对比',
          indicatorAnalysis: '指标分析',
          searchPolicyFiles: '搜索政策文件...',
          allCategories: '所有类别',
          fiscalTaxPolicy: '财税政策',
          industrialPolicy: '产业政策',
          financialPolicy: '金融政策',
          environmentalPolicy: '环保政策',
          allStatuses: '所有状态',
          active: '生效中',
          draft: '草案',
          expired: '已过期',
          filter: '筛选',
          totalPolicies: '政策总数',
          view: '查看',
          download: '下载',
          selectedPolicies: '已选择 {count} 项政策',
          compareAnalysis: '对比分析',
          gotoCompareCenter: '前往对比中心',
          compareCancel: '取消对比'
        },
        en: {
          policyQuery: 'Policy Query',
          intelligentPolicySearchSystem: 'Intelligent Policy Search and Query System',
          policyAnalysis: 'Policy Analysis',
          policyAnalysisSystem: 'Intelligent Policy Document Analysis and Comparison System',
          policyList: 'Policy List',
          policyComparison: 'Policy Comparison',
          indicatorAnalysis: 'Indicator Analysis',
          searchPolicyFiles: 'Search policy files...',
          allCategories: 'All Categories',
          fiscalTaxPolicy: 'Fiscal & Tax Policy',
          industrialPolicy: 'Industrial Policy',
          financialPolicy: 'Financial Policy',
          environmentalPolicy: 'Environmental Policy',
          allStatuses: 'All Statuses',
          active: 'Active',
          draft: 'Draft',
          expired: 'Expired',
          filter: 'Filter',
          totalPolicies: 'Total Policies',
          view: 'View',
          download: 'Download',
          selectedPolicies: 'Selected {count} policies',
          compareAnalysis: 'Compare Analysis',
          gotoCompareCenter: 'Go to Compare Center',
          compareCancel: 'Cancel Compare'
        }
      }
    },
    filteredPolicies() {
      // 由于后端已经处理了筛选逻辑，这里直接返回 policies
      // 不再进行前端重复筛选，避免数据不一致
      return this.policies;
    },
    tagMatchedPolicies() {
      if (this.selectedTags.length === 0) return this.policies.length

      return this.policies.filter(policy => {
        return this.selectedTags.some(selectedTag =>
          policy.tags.some(policyTag =>
            policyTag.toLowerCase().includes(selectedTag.toLowerCase()) ||
            selectedTag.toLowerCase().includes(policyTag.toLowerCase())
          )
        )
      }).length
    },

    // 后端分页，直接返回policies
    paginatedPolicies() {
      return this.policies;
    },
    totalPages() {
      return Math.max(1, Math.ceil(this.totalPolicyCount / this.pageSize));
    },

    tagBarOption() {
      // 统计所有政策 tags 词频，取前20
      const allTags = this.policies.flatMap(p => Array.isArray(p.tags) ? p.tags : []).filter(Boolean)
      const freq = {}
      allTags.forEach(tag => { freq[tag] = (freq[tag] || 0) + 1 })
      const sorted = Object.entries(freq).sort((a, b) => b[1] - a[1]).slice(0, 20)
      // 生成国际化标签和反查映射
      const tagOriginMap = {}
      const translatedTags = sorted.map(([tag]) => {
        const translated = this.t(tag)
        tagOriginMap[translated] = tag
        return translated
      })
      const selected = this.selectedTags.map(tag => this.t(tag))
      return {
        backgroundColor: 'transparent',
        grid: { left: 40, right: 20, top: 30, bottom: 40 },
        tooltip: { trigger: 'axis', backgroundColor: 'rgba(26, 37, 61, 0.95)', borderColor: '#00f5ff', textStyle: { color: '#fff', fontWeight: 'bold' } },
        xAxis: {
          type: 'category',
          data: translatedTags,
          axisLabel: {
            color: (val) => selected.includes(val) ? '#00e0c6' : '#b2e6f7',
            fontWeight: (val) => selected.includes(val) ? 'bold' : 'normal',
            fontSize: 12,
            rotate: 40,
            interval: 0,
            overflow: 'break',
            formatter: function (value) {
              return value.length > 6 ? value.slice(0, 6) + '\n' + value.slice(6) : value
            }
          },
          axisLine: { lineStyle: { color: '#00f5ff' } }
        },
        yAxis: {
          type: 'value',
          axisLabel: { color: '#b2e6f7' },
          axisLine: { lineStyle: { color: '#00f5ff' } },
          splitLine: { lineStyle: { color: 'rgba(0,245,255,0.12)' } }
        },
        series: [{
          type: 'bar',
          data: sorted.map(([tag, v]) => {
            const translated = this.t(tag)
            return {
              value: v,
              itemStyle: selected.includes(translated)
                ? { color: 'rgba(0,224,198,0.7)', borderRadius: [8, 8, 0, 0], shadowColor: '#00e0c6', shadowBlur: 8 }
                : { color: 'rgba(0,245,255,0.35)', borderRadius: [8, 8, 0, 0], shadowColor: '#00f5ff', shadowBlur: 4 }
            }
          }),
          barWidth: 28,
          emphasis: {
            itemStyle: {
              color: '#00e0c6',
              shadowColor: '#00e0c6',
              shadowBlur: 12
            }
          },
          animationDuration: 900
        }]
      }
    },

    visiblePages() {
      const current = this.currentPage
      const total = this.totalPages
      const pages = []

      if (total <= 7) {
        for (let i = 1; i <= total; i++) {
          pages.push(i)
        }
      } else {
        if (current <= 4) {
          for (let i = 1; i <= 5; i++) {
            pages.push(i)
          }
          pages.push('...')
          pages.push(total)
        } else if (current >= total - 3) {
          pages.push(1)
          pages.push('...')
          for (let i = total - 4; i <= total; i++) {
            pages.push(i)
          }
        } else {
          pages.push(1)
          pages.push('...')
          for (let i = current - 1; i <= current + 1; i++) {
            pages.push(i)
          }
          pages.push('...')
          pages.push(total)
        }
      }

      return pages
    }
  },
  data() {
    return {
      searchQuery: '',
      sortBy: 'date',
      currentPage: 1,
      pageSize: 10,
      selectedTags: [],
      popularTags: [],
      selectedPolicies: [],
      tagOriginMap: {},
      allTagOptions: [], // 后端返回的所有标签对象 {name, code}
      tagNameToCode: {}, // 中文名->编码映射
      groupedAllTags: {}, // {一级分类: [二级标签, ...]}，用于TagSelector
      showPolicyWindow: false,
      policyWindowData: null,
      policyWindowPosition: { x: 0, y: 0 },
      _policyWindowTimer: null,
      policies: [],
      totalPolicyCount: 0, // 新增
      isLoading: false, // 添加加载状态
      filters: {
        category: '',
        department: '',
        region: '',
        status: '',
        dateFrom: '',
        dateTo: ''
      },
      categoryOptions: [],
      departmentOptions: [],
      regionOptions: [],
      regionTree: [], // 多级地区树
      selectedRegionPath: [], // 选中的多级路径
      isFilterActive: false // 新增，标记是否有筛选条件激活
    }
  },
  created() {
    console.log('created called');
  },
  mounted() {
    // 初始化标签数据
    this.initializeTagsData();
    // 拉取后端所有标签映射
    axios.get('/api/policy/all-labels').then(res => {
      if (res.data && Array.isArray(res.data)) {
        this.allTagOptions = res.data;
        // 构建中文名->编码映射
        this.tagNameToCode = {};
        // 构建分组结构
        const grouped = {};
        res.data.forEach(item => {
          if (item.name && item.code) {
            this.tagNameToCode[item.name] = item.code;
            // 假设后端返回item.category为一级分类，否则全部归为“全部”
            const cat = item.category || '全部';
            if (!grouped[cat]) grouped[cat] = [];
            grouped[cat].push(item.name);
          }
        });
        this.groupedAllTags = grouped;
        // 热门标签：取所有分组下前8个标签
        this.popularTags = Object.values(grouped).flat().slice(0, 8);
      }
    }).catch(e => {
      console.error('拉取标签映射失败', e);
    });
    // 移除词云渲染相关
    window.addEventListener('resize', this.handleResize)
    // 首次挂载时根据当前语言翻译页面
    setCurrentLanguage(this.currentLanguage)
    translatePageContent(this.currentLanguage)
    // 页面挂载后自动拉取数据
    if (typeof this.performSearch === 'function') {
      console.log('mounted: performSearch is function, calling...');
      this.performSearch();
    } else {
      console.log('mounted: performSearch is NOT function:', typeof this.performSearch);
    }
  },
  beforeUnmount() {
    // 移除echarts实例相关
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    // 初始化标签数据
    async initializeTagsData() {
      try {
        console.log('正在获取后端标签数据...');
        const response = await axios.get('/api/policy/all-labels');
        const backendData = response.data;
        
        console.log('后端标签数据:', backendData);
        
        if (backendData && backendData.gb && backendData.zx) {
          // 构建标签名称到编码的映射
          this.tagNameToCode = {};
          this.allTagOptions = [];
          
          // 处理GB标签 (国标)
          const gbLabels = {};
          if (backendData.gb.level1) {
            backendData.gb.level1.forEach(item => {
              if (item.tagName) {
                gbLabels[item.tagName] = [];
                this.tagNameToCode[item.tagName] = String(item.tagNumber);
                this.allTagOptions.push({
                  name: item.tagName,
                  code: String(item.tagNumber),
                  category: 'GB国标',
                  level: 1
                });
              }
            });
          }
          
          if (backendData.gb.level2) {
            backendData.gb.level2.forEach(item => {
              if (item.tagName && item.gbIndustry2) {
                this.tagNameToCode[item.tagName] = item.gbIndustry2;
                this.allTagOptions.push({
                  name: item.tagName,
                  code: item.gbIndustry2,
                  category: 'GB国标',
                  level: 2,
                  parentId: item.gbIndustry1
                });
                
                // 找到对应的一级分类
                const parent = backendData.gb.level1.find(l1 => l1.tagNumber === item.gbIndustry1);
                if (parent && gbLabels[parent.tagName]) {
                  gbLabels[parent.tagName].push(item.tagName);
                }
              }
            });
          }
          
          // 处理ZX标签 (战新)
          const zxLabels = {};
          if (backendData.zx.level1) {
            backendData.zx.level1.forEach(item => {
              if (item.tagName) {
                zxLabels[item.tagName] = [];
                this.tagNameToCode[item.tagName] = String(item.tagNumber);
                this.allTagOptions.push({
                  name: item.tagName,
                  code: String(item.tagNumber),
                  category: 'ZX战新',
                  level: 1
                });
              }
            });
          }
          
          if (backendData.zx.level2) {
            backendData.zx.level2.forEach(item => {
              if (item.tagName && item.zxPolicy2) {
                this.tagNameToCode[item.tagName] = item.zxPolicy2;
                this.allTagOptions.push({
                  name: item.tagName,
                  code: item.zxPolicy2,
                  category: 'ZX战新',
                  level: 2,
                  parentId: item.zxPolicy1
                });
                
                // 找到对应的一级分类
                const parent = backendData.zx.level1.find(l1 => l1.tagNumber === item.zxPolicy1);
                if (parent && zxLabels[parent.tagName]) {
                  zxLabels[parent.tagName].push(item.tagName);
                }
              }
            });
          }
          
          // 合并GB和ZX标签
          this.groupedAllTags = { ...gbLabels, ...zxLabels };
          
          // 设置热门标签 (取各分类的前2个二级标签)
          this.popularTags = Object.values(this.groupedAllTags)
            .flat()
            .slice(0, 10);
          
          console.log('标签数据初始化完成:', {
            groupedAllTags: this.groupedAllTags,
            tagNameToCode: this.tagNameToCode,
            popularTags: this.popularTags,
            totalOptions: this.allTagOptions.length
          });
          
        } else {
          console.warn('后端标签数据格式不正确:', backendData);
        }
      } catch (error) {
        console.error('获取标签数据失败:', error);
        // 设置默认值以防止错误
        this.groupedAllTags = {};
        this.popularTags = [];
        this.tagNameToCode = {};
        this.allTagOptions = [];
      }
    },
    
    // 解决Vue警告：handleMaxSelectionReached
    handleMaxSelectionReached() {
      this.$toast?.error?.('最多只能选择10个标签') || alert('最多只能选择10个标签');
    },
    
    // 获取政策显示标签
    getDisplayTags(policy) {
      console.log('getDisplayTags调用 - policy:', policy);
      console.log('allTagOptions长度:', this.allTagOptions.length);
      
      if (Array.isArray(policy.tags) && policy.tags.length > 0) {
        console.log('使用policy.tags:', policy.tags);
        return policy.tags.filter(Boolean);
      }
      
      // 如果没有 tags 字段，从其他字段构建标签
      const tags = [];
      
      // 处理新的数组格式：gbIndustry2List 和 zxIndustry2List（驼峰命名）
      if (Array.isArray(policy.gbIndustry2List)) {
        console.log('处理gbIndustry2List:', policy.gbIndustry2List);
        policy.gbIndustry2List.forEach(code => {
          if (code) {
            const gbName = this.getTagNameByCode(code);
            console.log(`GB标签 ${code} -> ${gbName}`);
            if (gbName) tags.push(gbName);
          }
        });
      }
      
      if (Array.isArray(policy.zxIndustry2List)) {
        console.log('处理zxIndustry2List:', policy.zxIndustry2List);
        policy.zxIndustry2List.forEach(code => {
          if (code) {
            const zxName = this.getTagNameByCode(code);
            console.log(`ZX标签 ${code} -> ${zxName}`);
            if (zxName) tags.push(zxName);
          }
        });
      }
      
      // 处理下划线命名格式：gb_industry_2_list 和 zx_industry_2_list
      if (Array.isArray(policy.gb_industry_2_list)) {
        console.log('处理gb_industry_2_list:', policy.gb_industry_2_list);
        policy.gb_industry_2_list.forEach(code => {
          if (code) {
            const gbName = this.getTagNameByCode(code);
            console.log(`GB标签(下划线) ${code} -> ${gbName}`);
            if (gbName) tags.push(gbName);
          }
        });
      }
      
      if (Array.isArray(policy.zx_industry_2_list)) {
        console.log('处理zx_industry_2_list:', policy.zx_industry_2_list);
        policy.zx_industry_2_list.forEach(code => {
          if (code) {
            const zxName = this.getTagNameByCode(code);
            console.log(`ZX标签(下划线) ${code} -> ${zxName}`);
            if (zxName) tags.push(zxName);
          }
        });
      }
      
      // 兼容旧的单个字段格式
      if (policy.gbIndustry2) {
        const gbName = this.getTagNameByCode(policy.gbIndustry2);
        if (gbName) tags.push(gbName);
      }
      
      if (policy.zxIndustry2) {
        const zxName = this.getTagNameByCode(policy.zxIndustry2);
        if (zxName) tags.push(zxName);
      }
      
      // 兼容其他字段格式
      if (policy.gb_industry_2) {
        const gbName = this.getTagNameByCode(policy.gb_industry_2);
        if (gbName) tags.push(gbName);
      }
      
      if (policy.zx_industry_2) {
        const zxName = this.getTagNameByCode(policy.zx_industry_2);
        if (zxName) tags.push(zxName);
      }
      
      console.log('最终标签列表:', [...new Set(tags)]);
      return [...new Set(tags)]; // 去重
    },
    
    // 新增：通过编码查找标签中文名
    getTagNameByCode(code) {
      const item = this.allTagOptions.find(option => option.code === code);
      return item ? item.name : null;
    },
    
    // 新增：通过中文名查找编码
    getCodeByTagName(name) {
      return this.tagNameToCode[name] || null;
    },
    
    // 新增：标签选择变化处理
    handleTagsChange(tags) {
      console.log('标签选择变化:', tags);
      this.selectedTags = tags;
      this.performSearch(true);
    },
    
    // 新增：点击标签快速筛选
    quickFilterByTag(tag) {
      if (!this.selectedTags.includes(tag)) {
        this.selectedTags.push(tag);
        this.performSearch(true);
      }
    },
    // 更新 tagOriginMap，仅统计当前policies的tags映射
    updateTagOriginMap() {
      // 统计所有政策 tags 词频，取前20
      const allTags = this.policies.flatMap(p => Array.isArray(p.tags) ? p.tags : []).filter(Boolean)
      const freq = {}
      allTags.forEach(tag => { freq[tag] = (freq[tag] || 0) + 1 })
      const sorted = Object.entries(freq).sort((a, b) => b[1] - a[1]).slice(0, 20)
      // 生成国际化标签和反查映射
      const tagOriginMap = {}
      sorted.forEach(([tag]) => {
        const translated = this.t(tag)
        tagOriginMap[translated] = tag
      })
      this.tagOriginMap = tagOriginMap
    },
    formatDate(dateString) {
      if (!dateString) return '-';
      try {
        const date = new Date(dateString);
        if (isNaN(date.getTime())) return dateString;
        
        return this.currentLanguage === 'zh' 
          ? `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
          : date.toLocaleDateString('en-US', { 
              year: 'numeric', 
              month: 'short', 
              day: 'numeric' 
            });
      } catch (e) {
        return dateString;
      }
    },

    // 政策对比相关方法
    async navigateToCompareCenter() {
      if (this.selectedPolicies.length >= 2) {
        try {
          console.log('准备传递的政策IDs:', this.selectedPolicies)
          
          // 获取选中政策的完整信息
          const selectedPolicyData = this.policies.filter(policy => 
            this.selectedPolicies.includes(policy.id)
          )
          
          console.log('选中的政策完整信息:', selectedPolicyData)
          
          // 将选中的政策信息存储到sessionStorage中
          sessionStorage.setItem('preSelectedPolicies', JSON.stringify(selectedPolicyData))
          
          // 跳转到政策中心的对比分析标签页
          this.$router.push({
            path: '/policy-center',
            query: { 
              tab: 'compare',
              selectedIds: this.selectedPolicies.join(',')
            }
          });
          
          console.log('成功跳转到对比页面')
        } catch (e) {
          console.error('跳转到对比页面失败', e);
        }
      } else {
        console.log('选中政策数量不足，无法对比')
      }
    },
    
    handleCompareClick() {
      console.log('=== 处理对比点击 ===')
      console.log('选中政策数量:', this.selectedPolicies.length)
      if (this.selectedPolicies.length >= 2) {
        this.navigateToCompareCenter()
      }
    },
    
    clearSelection() {
      console.log('=== 清除选择 ===')
      this.selectedPolicies = []
    },

    t(key, params = {}) {
      let text = this.translations[this.currentLanguage.value || this.currentLanguage][key] || key
      Object.keys(params).forEach(param => {
        text = text.replace(`{${param}}`, params[param])
      })
      return text
    },

    getAllLevel2Tags() {
      return Object.values(tagService.tags).flat()
    },

    async performSearch(resetPage = false) {
      console.log('performSearch method defined');
      if (resetPage) this.currentPage = 1;
      // 设置加载状态
      this.isLoading = true;
      // 将selectedTags（中文）转为编码
      let tagCodes = [];
      if (this.selectedTags && this.selectedTags.length && this.tagNameToCode) {
        tagCodes = this.selectedTags
          .map(name => this.tagNameToCode[name])
          .filter(code => code); // 过滤掉undefined的编码
      }
      
      console.log('搜索参数 - 选中标签(中文):', this.selectedTags);
      console.log('搜索参数 - 转换后编码:', tagCodes);
      console.log('performSearch called, currentPage:', this.currentPage, 'pageSize:', this.pageSize, 'filters:', this.filters, 'selectedTags:', this.selectedTags, 'tagCodes:', tagCodes);
      try {
        // 构建查询参数，tags用逗号分隔字符串
        const params = {
          keyword: this.searchQuery && this.searchQuery.trim() ? this.searchQuery.trim() : undefined,
          category: this.filters.category || undefined,
          department: this.filters.department || undefined,
          region: this.filters.region || undefined,
          dateFrom: this.filters.dateFrom || undefined,
          dateTo: this.filters.dateTo || undefined,
          tags: tagCodes.length ? tagCodes.join(',') : undefined,
          status: this.filters.status || undefined,
          page: this.currentPage,
          size: this.pageSize
        };
        const cleanParams = Object.fromEntries(Object.entries(params).filter(([_, v]) => v !== undefined && v !== ''));
        const res = await axios.get('/api/policy/filter', { params: cleanParams });
        console.log('接口原始返回', res.data);
        const dataList = Array.isArray(res.data.list) ? res.data.list : [];
        console.log('第一个政策原始数据:', dataList[0]);
        console.log('第一个政策的所有字段:', dataList[0] ? Object.keys(dataList[0]) : '无数据');
        // 补充id字段，兼容后端多种字段名，过滤无效政策
        this.policies = dataList
          .filter(p => p && (p.policyId || p.id))
          .map(p => {
            // 处理标签字段，支持编码到中文名的转换
            let tags = [];
            if (Array.isArray(p.tags) && p.tags.length > 0) {
              // 如果后端直接返回了标签数组，检查是否需要转换
              tags = p.tags.filter(Boolean).map(tag => {
                // 如果是编码格式（如 "1-1", "2-3"），尝试转换为中文名
                if (typeof tag === 'string' && tag.includes('-')) {
                  return this.getTagNameByCode(tag) || tag;
                }
                return tag;
              });
            } else {
              // 如果没有tags字段，尝试从gb/zx字段构建
              if (p.gbIndustry2) {
                const gbCode = String(p.gbIndustry2);
                const gbName = this.getTagNameByCode(gbCode);
                if (gbName) tags.push(gbName);
              }
              if (p.zxIndustry2) {
                const zxCode = String(p.zxIndustry2);
                const zxName = this.getTagNameByCode(zxCode);
                if (zxName) tags.push(zxName);
              }
              // 兼容其他字段格式
              if (p.gb_industry_2) {
                const gbName = this.getTagNameByCode(p.gb_industry_2);
                if (gbName) tags.push(gbName);
              }
              if (p.zx_industry_2) {
                const zxName = this.getTagNameByCode(p.zx_industry_2);
                if (zxName) tags.push(zxName);
              }
              // 兼容其他字段
              if (p.industryType1) tags = tags.concat(String(p.industryType1).split(/[，,]/).map(s => s.trim()).filter(Boolean));
              if (p.industryType2) tags = tags.concat(String(p.industryType2).split(/[，,]/).map(s => s.trim()).filter(Boolean));
            }
            // 地区、类别、部门兼容多字段
            let region = p.address2 || p.address1 || p.address_2 || p.address_1 || '';
            let category = p.type || p.category || '';
            let department = p.department || '';
            // 兼容后端policyId字段，补充id字段
            // 兼容publishTime、writeTime等时间字段
            let publishDate = p.publishDate || p.publishTime || p.publish_time || '';
            let writeTime = p.writeTime || p.write_time || '';
            return { ...p, id: p.policyId || p.id, tags, region, category, department, publishDate, writeTime };
          });
        this.totalPolicyCount = typeof res.data.total === 'number' ? res.data.total : this.policies.length;
      } catch (e) {
        console.error('performSearch error', e);
        this.policies = [];
        this.totalPolicyCount = 0;
        this.$toast?.error?.('筛选失败，请检查网络或参数') || alert('筛选失败，请检查网络或参数');
        console.error('筛选失败', e);
      } finally {
        // 重置加载状态
        this.isLoading = false;
      }
      // 无论是否异常都输出policies内容
      console.log('policies after fetch', this.policies);
      this.categoryOptions = [...new Set(this.policies.map(p => p.category).filter(v => v && typeof v === 'string' && v.trim() !== ''))];
      this.departmentOptions = [...new Set(this.policies.map(p => p.department).filter(v => v && typeof v === 'string' && v.trim() !== ''))];
      this.regionOptions = [...new Set(this.policies.map(p => p.region).filter(v => v && typeof v === 'string' && v.trim() !== ''))];
      this.regionTree = this.buildRegionTree(this.policies);
    },
    previousPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
        this.performSearch(); // 不传递 resetPage 参数，保持当前页码逻辑
      }
    },
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
        this.performSearch(); // 不传递 resetPage 参数，保持当前页码逻辑
      }
    },
    goToPage(page) {
      if (typeof page === 'number' && page !== this.currentPage) {
        this.currentPage = page;
        this.performSearch(); // 不传递 resetPage 参数，保持当前页码逻辑
      }
    },
    handleTagsChange(tags) {
      this.selectedTags = tags;
      this.performSearch(true);
    },
    handleRegionSelect(pathArr) {
      this.selectedRegionPath = pathArr;
      this.filters.region = pathArr.length ? pathArr[pathArr.length - 1] : '';
      this.performSearch(true);
    },
    applyQuickFilter(tag) {
      this.searchQuery = tag;
      this.performSearch(true);
    },
    handleKeyPress(event) {
      if (event.key === 'Enter') {
        this.performSearch(true);
      }
    },
    onBarClick(params) {
      if (params && params.name) {
        this.toggleTag(params.name)
      }
    },

    getStatusClass(status) {
      const classes = {
        '生效中': 'status-success',
        '即将生效': 'status-warning',
        '草案': 'status-info',
        '已过期': 'status-error'
      }
      return classes[status] || 'status-info'
    },

    viewPolicy(policy) {
      // 跳转到政策详情页面，校验id有效性
      const id = policy && policy.id ? String(policy.id) : '';
      if (!id || id === 'null' || id === 'undefined') {
        this.$toast?.error?.('政策ID无效，无法跳转详情页') || alert('政策ID无效，无法跳转详情页');
        return;
      }
      this.$router.push({ name: 'PolicyDetail', params: { id } });
    },

    downloadPolicy(policy) {
      // 下载政策文件
      console.log('下载政策:', policy.title)
    },

    collectPolicy(policy) {
      // 收藏政策
      console.log('收藏政策:', policy.title)
    },

    toggleTag(tag) {
      const index = this.selectedTags.indexOf(tag)
      if (index > -1) {
        this.selectedTags.splice(index, 1)
      } else {
        this.selectedTags.push(tag)
      }
      // 修复：立即触发搜索
      this.performSearch()
    },

    // 政策选择相关方法
    isSelected(policy) {
      return this.selectedPolicies.includes(policy.id)
    },

    togglePolicySelection(policy) {
      const index = this.selectedPolicies.indexOf(policy.id)
      if (index > -1) {
        this.selectedPolicies.splice(index, 1)
        console.log('取消选择政策:', policy.title)
      } else {
        this.selectedPolicies.push(policy.id)
        console.log('选择政策:', policy.title)
      }
      
      console.log('当前已选择政策数量:', this.selectedPolicies.length)
    },

    // 调试方法
    debugSelection() {
      console.log('=== 政策选择调试信息 ===');
      console.log('选中的政策数量:', this.selectedPolicies.length);
      console.log('选中的政策ID:', this.selectedPolicies.map(p => p.id));
      console.log('选中的政策标题:', this.selectedPolicies.map(p => p.title));
      console.log('对比按钮是否应该显示:', this.selectedPolicies.length > 0);
      console.log('对比按钮是否应该启用:', this.selectedPolicies.length >= 2);
    },

    // 悬浮弹窗逻辑优化
    onPolicyTitleEnter(policy, event) {
      clearTimeout(this._policyWindowTimer)
      this._isPolicyWindowHover = false // 标记鼠标不在弹窗
      this._isPolicyTitleHover = true   // 标记鼠标在标题
      this._policyWindowTimer = setTimeout(() => {
        this.policyWindowData = policy
        // 计算弹窗位置
        const rect = event.target.getBoundingClientRect()
        const popupWidth = 420 // 假设弹窗宽度
        const popupHeight = 600 // 假设弹窗高度
        const padding = 16
        let x = rect.left + window.scrollX
        let y = rect.bottom + window.scrollY + 8

        // 判断下边是否超出
        const viewportHeight = window.innerHeight
        if (y + popupHeight + padding > window.scrollY + viewportHeight) {
          // 超出则弹窗显示在屏幕中间靠右一点
          x = window.scrollX + window.innerWidth * 0.6 - popupWidth / 2
          y = window.scrollY + window.innerHeight / 2 - popupHeight / 2
          // 防止超出右侧
          if (x + popupWidth > window.scrollX + window.innerWidth - padding) {
            x = window.scrollX + window.innerWidth - popupWidth - padding
          }
          // 防止超出左侧
          if (x < window.scrollX + padding) {
            x = window.scrollX + padding
          }
          // 防止超出顶部
          if (y < window.scrollY + padding) {
            y = window.scrollY + padding
          }
        }

        this.policyWindowPosition = { x, y }
        this.showPolicyWindow = true
      }, 300)
    },
    onPolicyTitleLeave() {
      this._isPolicyTitleHover = false
      clearTimeout(this._policyWindowTimer)
      // 只有当鼠标不在标题和弹窗都不在时才隐藏
      this._policyWindowTimer = setTimeout(() => {
        if (!this._isPolicyTitleHover && !this._isPolicyWindowHover) {
          this.showPolicyWindow = false
        }
      }, 300)
    },
    // 鼠标进入弹窗，清除隐藏定时器并标记悬浮
    onPolicyWindowEnter() {
      clearTimeout(this._policyWindowTimer)
      this._isPolicyWindowHover = true
    },
    // 鼠标离开弹窗，0.3秒后隐藏并取消悬浮标记
    onPolicyWindowLeave() {
      this._isPolicyWindowHover = false
      clearTimeout(this._policyWindowTimer)
      this._policyWindowTimer = setTimeout(() => {
        if (!this._isPolicyTitleHover && !this._isPolicyWindowHover) {
          this.showPolicyWindow = false
        }
      }, 300)
    },
    handleGoDetail(id) {
      if (!id || typeof id !== 'string' || id === 'null' || id === 'undefined') {
        this.$toast?.error?.('政策ID无效，无法跳转详情页') || alert('政策ID无效，无法跳转详情页');
        return;
      }
      this.$router.push({ name: 'PolicyDetail', params: { id: id + '' } });
    },
    // 字段兼容显示方法
    safeField(val, fallback = '-') {
      if (val === undefined || val === null || val === '') return fallback
      return val
    },
    safeDate(val, fallback = '-') {
      if (!val) return fallback
      try {
        const d = typeof val === 'string' ? new Date(val) : val
        if (isNaN(d.getTime())) return fallback
        return d.toLocaleDateString('zh-CN')
      } catch { return fallback }
    },
    // 前端推断政策状态
    inferPolicyStatus(policy) {
  const now = new Date();
  const publishDate = policy.publishDate ? new Date(policy.publishDate) : null;
  const startTime = policy.effectiveDate ? new Date(policy.effectiveDate) : null;
  const endTime = policy.expiryDate ? new Date(policy.expiryDate) : null;
  const writeTime = policy.writeTime ? new Date(policy.writeTime) : null;
  
  // 草案：当前时间在成文时间到公布日期之间
  if (writeTime && publishDate && now >= writeTime && now < publishDate) return '草案'
  
  // 即将生效：当前时间在公布日期到生效日期之间
  if (publishDate && startTime && now >= publishDate && now < startTime) return '即将生效'
  
  // 生效中：当前时间在生效日期到失效日期之间
  if (startTime && (!endTime || now < endTime) && now >= startTime) return '生效中'
  
  // 已过期：当前时间晚于失效日期
  if (endTime && now >= endTime) return '已过期'
  
  // 兜底：根据发布日期判断
  if (publishDate && now >= publishDate) return '生效中'
  
  return '草案'
},

    buildRegionTree(policies) {
      if (policies.length === 0) return [];

      const root = {};
      policies.forEach(p => {
        const levels = [p.address1, p.address2, p.address3, p.address4, p.address5, p.address6]
          .filter(l => typeof l === 'string' && l.trim() !== '');
        if (levels.length === 0) return;
        let node = root;
        levels.forEach((level, i) => {
          if (!node[level]) node[level] = { _children: {}, _isLeaf: i === levels.length - 1 };
          node = node[level]._children;
        });
      });
      function toArr(obj) {
        return Object.entries(obj).map(([name, val]) => ({
          name,
          isLeaf: val._isLeaf,
          children: toArr(val._children)
        }));
      }
      return toArr(root);
    }
  },
  beforeUnmount() {
    // 移除echarts实例相关
    window.removeEventListener('resize', this.handleResize)
  },
  watch: {
    // policies 变化时只更新 tagOriginMap，不再重排词云
    policies: {
      handler() {
        this.updateTagOriginMap();
      },
      deep: true
    },
    pageSize(val, oldVal) {
      if (val !== oldVal) {
        this.currentPage = 1;
        this.performSearch(true);
      }
    },
    currentPage(newPage) {
      this.performSearch();
    },
  }
}
</script>

<style scoped>

:deep() {
  user-select: text;
  -webkit-user-select: text;
  caret-color: transparent;
  cursor: default;
}

:deep(button) {
  cursor: pointer;
}

:deep(.policy-content) {
  ::selection {
    color: inherit;
  }
}

.line-clamp-3 {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.status-success {
  padding-left: 0.5rem;
  padding-right: 0.5rem;
  padding-top: 0.25rem;
  padding-bottom: 0.25rem;
  background-color: rgba(34,197,94,0.125); /* bg-green-500/20 */
  color: #6ee7b7; /* text-green-300 */
  border-radius: 0.375rem;
  font-size: 0.75rem;
  line-height: 1rem;
}

.status-warning {
  padding-left: 0.5rem;
  padding-right: 0.5rem;
  padding-top: 0.25rem;
  padding-bottom: 0.25rem;
  background-color: rgba(250,204,21,0.125); /* bg-yellow-500/20 */
  color: #fde68a; /* text-yellow-300 */
  border-radius: 0.375rem;
  font-size: 0.75rem;
  line-height: 1rem;
}

.status-info {
  padding-left: 0.5rem;
  padding-right: 0.5rem;
  padding-top: 0.25rem;
  padding-bottom: 0.25rem;
  background-color: rgba(59,130,246,0.125); /* bg-blue-500/20 */
  color: #93c5fd; /* text-blue-300 */
  border-radius: 0.375rem;
  font-size: 0.75rem;
  line-height: 1rem;
}

.status-error {
  padding-left: 0.5rem;
  padding-right: 0.5rem;
  padding-top: 0.25rem;
  padding-bottom: 0.25rem;
  background-color: rgba(239,68,68,0.125); /* bg-red-500/20 */
  color: #fca5a5; /* text-red-300 */
  border-radius: 0.375rem;
  font-size: 0.75rem;
  line-height: 1rem;
}
.glass-card {
  background: var(--color-glassBg);
  backdrop-filter: blur(12px);
  border: 1px solid var(--color-border);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.36);
}

.cyber-button {
  background: var(--gradient-accent);
  border: 1px solid var(--color-borderHover);
  color: var(--color-accent);
  padding: 0.5rem 1rem;
  border-radius: 6px;
  transition: all 0.3s;
}

.cyber-button:hover:not(:disabled) {
  background: var(--gradient-accent);
  box-shadow: 0 0 12px var(--color-glow);
}

.text-primary {
  color: var(--color-textPrimary);
}

.text-accent {
  color: var(--color-accent);
}

.chart-container {
  width: 100%;
  height: 150px;
  min-height: 100px;
  animation: fadeInUp 0.8s cubic-bezier(.4,2.2,.2,1);
  cursor: pointer;
}

.wordcloud-container {
  width: 100%;
  height: 150px;
  min-height: 100px;
  background: var(--gradient-card);
  border-radius: 14px;
  box-shadow: 0 0 24px var(--color-glow);
  animation: fadeInUp 1.2s cubic-bezier(.4,2.2,.2,1);
}

.my-element {
  background-color: var(--color-primary);
  color: var(--color-textPrimary);
  border: 1px solid var(--color-border);
}
.glass-card {
  background: var(--glass-bg, rgba(26, 35, 61, 0.7));
  backdrop-filter: blur(12px);
  border: 1px solid var(--glass-border, rgba(0, 245, 255, 0.1));
  box-shadow: 0 8px 32px var(--glass-shadow, rgba(0, 0, 0, 0.36));
}
.theme-light .glass-card {
  --glass-bg: rgba(255,255,255,0.85);
  --glass-border: rgba(0,115,230,0.12);
  --glass-shadow: rgba(0,115,230,0.08);
  color: #222;
}
.theme-light .cyber-button {
  background: linear-gradient(135deg, rgba(0,115,230,0.08), rgba(0,245,255,0.08));
  border: 1px solid rgba(0,115,230,0.18);
  color: #0073e6;
}
.theme-light .cyber-button:hover:not(:disabled) {
  background: linear-gradient(135deg, rgba(0,115,230,0.15), rgba(0,245,255,0.15));
  box-shadow: 0 0 12px rgba(0,115,230,0.12);
}
.theme-light .status-success {
  background-color: rgba(34,197,94,0.12);
  color: #22c55e;
}
.theme-light .status-warning {
  background-color: rgba(250,204,21,0.12);
  color: #eab308;
}
.theme-light .status-info {
  background-color: rgba(59,130,246,0.12);
  color: #2563eb;
}
.theme-light .status-error {
  background-color: rgba(239,68,68,0.12);
  color: #ef4444;
}
.theme-light .text-white,
.theme-light .text-white\/70,
.theme-light .text-white\/80,
.theme-light .text-white\/50 {
  color: #222 !important;
}
.theme-light .text-electric-500 {
  color: #0073e6 !important;
}
.theme-light .text-electric-400 {
  color: #22c55e !important;
}
.theme-light .bg-electric-500 {
  background-color: #e0f7fa !important;
}
.theme-light .bg-electric-400 {
  background-color: #b2ebf2 !important;
}
</style>
<style>
/* 浅色模式下智能解读内容字体适配 */
.theme-light .text-white\/90,
.theme-light .text-white,
.theme-light .text-white\/80,
.theme-light .text-white\/70,
.theme-light .text-white\/50 {
  color: #222 !important;
}
.theme-light .ai-interpret-content {
  color: #222 !important;
  background: #f7fafc !important;
  border-radius: 8px;
  padding: 1em;
  font-size: 1em;
  line-height: 1.8;
  box-shadow: 0 2px 12px #e0e7ef22;
}
</style>
<style>
/* 浅色模式下政策列表高对比度美观适配 */
.theme-light .glass-card {
  background: #fff !important;
  color: #222 !important;
  border: 1px solid #e0e7ef !important;
  box-shadow: 0 4px 24px #e0e7ef55 !important;
}
.theme-light .text-white,
.theme-light .text-white\/70,
.theme-light .text-white\/80,
.theme-light .text-white\/50 {
  color: #222 !important;
}
.theme-light .text-electric-500 {
  color: #0073e6 !important;
}
.theme-light .text-yellow-400 {
  color: #eab308 !important;
}
.theme-light .bg-electric-500\/20,
.theme-light .bg-tech-blue-500\/20 {
  background: #e0f7fa !important;
  color: #007a8a !important;
  border: 1px solid #b2e6f7 !important;
}
.theme-light .text-electric-300 {
  color: #0097a7 !important;
}
.theme-light .bg-yellow-500 {
  background: #fffbe6 !important;
  color: #b58105 !important;
}
.theme-light .bg-electric-500 {
  background: #e0f7fa !important;
  color: #007a8a !important;
}
.theme-light .bg-electric-600 {
  background: #b2ebf2 !important;
  color: #007a8a !important;
}
.theme-light .cyber-button {
  background: linear-gradient(135deg, #e6f7ff 0%, #f7fafc 100%) !important;
  color: #0073e6 !important;
  border: 1px solid #b2e6f7 !important;
}
.theme-light .cyber-button:disabled {
  background: #f7fafc !important;
  color: #bbb !important;
  border: 1px solid #e0e7ef !important;
}
.theme-light .rounded,
.theme-light .rounded-lg,
.theme-light .rounded-full {
  border-radius: 8px !important;
}
.theme-light .hover\:cyber-glow:hover {
  box-shadow: 0 0 0 2px #b2e6f7, 0 4px 24px #e0e7ef55 !important;
}
.theme-light .text-cyber-50 {
  color: #fff !important;
}
.theme-light .text-yellow-400 {
  color: #eab308 !important;
}
.theme-light .text-tech-blue-300 {
  color: #0073e6 !important;
}
.theme-light .bg-tech-blue-500\/20 {
  background: #e6f7ff !important;
  color: #0073e6 !important;
}
.theme-light .bg-yellow-500 {
  background: #fffbe6 !important;
  color: #b58105 !important;
}
.theme-light .status-success {
  background: #e6ffed !important;
  color: #22c55e !important;
}
.theme-light .status-warning {
  background: #fffbe6 !important;
  color: #eab308 !important;
}
.theme-light .status-info {
  background: #e6f7ff !important;
  color: #0073e6 !important;
}
.theme-light .status-error {
  background: #ffeaea !important;
  color: #ef4444 !important;
}
</style>
<style>
/* 浅色模式下标签chip、统计数字、输入框等高对比度适配 */
.theme-light .tag-chip,
.theme-light .bg-electric-500\/20,
.theme-light .bg-tech-blue-500\/20 {
  background: #e0f7fa !important;
  color: #007a8a !important;
  border: 1px solid #b2e6f7 !important;
  box-shadow: 0 1px 4px #b2e6f733;
}
.theme-light .text-electric-300 {
  color: #0097a8 !important;
}
.theme-light .glass-card .text-3xl {
  color: #00b8d9 !important;
}
.theme-light .cyber-input {
  background: #f7fafc !important;
  color: #222 !important;
  border-color: #b2e6f7 !important;
}
.theme-light .text-white,
.theme-light .text-white\/70,
.theme-light .text-white\/80,
.theme-light .text-white\/50 {
  color: #222 !important;
}
</style>
